# coding=utf-8

from datetime import datetime
from https.UploadPaths import UploadPaths
import base64
import json
import uuid
import requests
import os
import wave
import time

appid = "6374385998"
access_token = "Y0xgdtvKpvTSNxXWMtIWTzX31uoW8yWG"
cluster = "wbWpZwg_tM5GkVsCXCiI7SEyhyY_KMr3"

voice_type = "BV405_streaming"
host = "openspeech.bytedance.com"
api_url = f"https://{host}/api/v1/tts"

header = {"Authorization": f"Bearer;{access_token}"}

request_json = {
    "app": {
        "appid": appid,
        "token": access_token,
        "cluster": "volcano_tts"
    },
    "user": {
        "uid": str(uuid.uuid4())
    },
    "audio": {
        "voice_type": voice_type,
        "emotion": "",
        "encoding": "wav",
        "speed_ratio": 0.8,
        "volume_ratio": 1.0,
        "pitch_ratio": 1.0,
    },
    "request": {
        "reqid": str(uuid.uuid4()),
        "text": "字节跳动语音合成",
        "text_type": "plain",
        "operation": "query",
        "with_frontend": 1,
        "frontend_type": "unitTson",
        "silence_duration": 125

    }
}


def task_process(text, voice_type, emotion_category, speed_ratio, is_last_item):
    try:
        time.sleep(0.4)
        if is_last_item:
            # 执行最后一项的逻辑
            request_json['request']['silence_duration'] = 3000
        else:
            request_json['request']['silence_duration'] = 125
        request_json['audio']['voice_type'] = voice_type
        request_json['audio']['emotion'] = emotion_category
        request_json['audio']['speed_ratio'] = speed_ratio
        request_json['request']['text'] = text
        with requests.Session() as session:
            resp = session.post(api_url, json.dumps(request_json), headers=header, verify=False)
        resp.raise_for_status()  # 检查是否有错误状态码

        if "data" in resp.json():
            data = resp.json()["data"]

        upload_paths = UploadPaths()
        upload_folder = upload_paths.get_path("temp")
        current_time = datetime.now().strftime("%Y%m%d%H%M%S")
        file_path = os.path.join(upload_folder, current_time + str(uuid.uuid4()) + ".wav")

        with open(file_path, "wb") as file_to_save:
            file_to_save.write(base64.b64decode(data))
        print(file_path)
        duration = get_wav_duration(file_path, text)
        return {"text": text, "file_path": file_path, "duration": duration}
    except Exception as e:
        e.with_traceback()
    return None


def get_wav_duration(file_path, text):
    try:
        with wave.open(file_path, 'rb') as wavfile:
            # 获取采样率和采样点数量
            framerate = wavfile.getframerate()
            frames = wavfile.getnframes()

            # 计算时长（秒）
            duration = frames / float(framerate)

            print(f"WAV 文件时长：{duration} 秒,text:{text}")
            return duration
    except Exception as e:
        print(f"获取 WAV 文件时长失败：{e}")
        return None


if __name__ == '__main__':
    task_process("你又怎么能懂我小猩猩的孤独呢", "BV700_V2_streaming", "conniving", 0.8)
